package com.cn.ycy.token;


import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class meituan {

  public static void main(String[] args) {
    String s = generateSign(new HashMap<>(), "1", "MD5");
    System.out.println(s);
  }

  public static String generateSign(Map<String, String> params, String appSecret, String signMethod) {
    // 第一步：参数排序
    List<String> keys = new ArrayList<>();
    for (Map.Entry<String, String> entry : params.entrySet()) {
      if (StringUtils.isNotEmpty(entry.getValue())) {
        keys.add(entry.getKey());
      }
    }
    Collections.sort(keys);
    // 第二步：把所有参数名和参数值串在一起
    StringBuilder sb = new StringBuilder();
    if (StringUtils.isNotEmpty(appSecret)) {
      sb.append(appSecret);
    }
    for (String key : keys) {
      sb.append(key).append(params.get(key).trim());
    }
    if (StringUtils.isNotEmpty(appSecret)) {
      sb.append(appSecret);
    }
    String encryptionKey = sb.toString().trim();
    // 第三步：加签
    if (signMethod.equals("MD5")) {
      try {
        String sign = genMd5(encryptionKey);
        return sign;
      } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    } else {
      //开发者暂不需支持，支持MD5即可
      return "";
    }
  }

  public static String genMd5(String info) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    // SHA1签名生成
    MessageDigest md = MessageDigest.getInstance("SHA-1");

    MessageDigest md5 = MessageDigest.getInstance("MD5");
    byte[] infoBytes = info.getBytes();
    md5.update(infoBytes);
    byte[] sign = md5.digest();
//    System.out.println(new BigInteger(1, sign).toString(10) + " 1111");
    System.out.println(new BigInteger(1, sign).toString(16) + " 1111");
    return byteArrayToHex(sign);
  }

  public static String byteArrayToHex(byte[] bytes) {
    StringBuilder sign = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
      String hex = Integer.toHexString(bytes[i] & 0xFF);
      if (hex.length() == 1) {
        sign.append("0");
      }
      sign.append(hex.toLowerCase());
    }
    return sign.toString();
  }

}
